package handlers

import (
	"go-mysql-rec/models"
	"net/http"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)

//GetToken get user's access token
func (h *Handler) GetToken() echo.HandlerFunc {
	return func(c echo.Context) error {
		var user models.User
		c.Bind(&user)

		users := models.Login(h.DB, user.UserName, user.PassWord)
		if len(users.Users) == 1 {
			claims := &JwtCustomClaims{
				users.Users[0].UserName,
				users.Users[0].ID,
				jwt.StandardClaims{
					ExpiresAt: time.Now().Add(time.Hour * 72).Unix(),
				},
			}

			// Create token with claims
			token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

			t, err := token.SignedString([]byte("secret"))
			if err != nil {
				return err
			}

			return c.JSON(http.StatusOK, map[string]string{
				"token": t,
			})
		}
		return c.JSON(http.StatusOK, echo.ErrUnauthorized)

	}
}
